package com.project.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.project.dto.MaterialDTO;
import com.project.dto.MaterialPageQueryDTO;
import com.project.entity.Materials;
import com.project.mapper.MaterialsMapper;
import com.project.result.PageResult;
import com.project.service.MaterialsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MaterialsServiceImpl implements MaterialsService {
    @Autowired
    private MaterialsMapper materialsMapper;

    @Override
    public void createMaterials(MaterialDTO dto) {

        Materials materials = new Materials();
        BeanUtils.copyProperties(dto, materials);
        materials.setStatus(0);
        materialsMapper.insert(materials);

    }

    @Override
    public void updateMaterials(MaterialDTO dto) {
        Materials materials = new Materials();
        BeanUtils.copyProperties(dto, materials);
        materialsMapper.updateById(materials);
    }

    @Override
    public void updateStatus(Integer status, Integer id) {
        Materials update = Materials.builder()
                .materialId(id)
                .status(status)
                .build();


        materialsMapper.updateById(update);

    }

    @Override
    public void deleteMaterials(Integer id) {
        //判断材料是否存在
        Materials selectedById = materialsMapper.selectById(id);
        if (selectedById == null) {
            throw new RuntimeException("材料不存在");
        }

        //判断状态是否为停用 只有状态为 停用0 时才允许删除
        if (selectedById.getStatus() != 0) {
            throw new RuntimeException("请先停用该材料，再进行删除");

        }
        materialsMapper.deleteById(id);
    }


    @Override
    public PageResult pageQuery(MaterialPageQueryDTO queryDTO) {

        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());
        Page<Materials> pageQuery = materialsMapper.pageQuery(queryDTO);
        return new PageResult(pageQuery.getTotal(), pageQuery.getResult());
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        //判断材料ID是否为空
        if (ids == null || ids.isEmpty()) {
            throw new RuntimeException("材料ID不能为空");
        }

        for (Integer id : ids) {
            // 1. 判断材料是否存在
            Materials material = materialsMapper.selectById(id);
            if (material == null) {
                throw new RuntimeException("材料不存在");

            }

            // 2. 判断状态是否为停用（0）
            if (material.getStatus() != 0) {
                throw new RuntimeException("请先停用该材料，再进行删除");

            }

        }
        materialsMapper.deleteBatchIds(ids);
    }
}



